package com.gitee.faster.webdav.kernel.protocol.dispatcher;

import com.gitee.faster.webdav.common.constant.MethodEnum;
import com.gitee.faster.webdav.kernel.protocol.HttpExchange;
import com.gitee.faster.webdav.kernel.resource.Resource;
import com.gitee.faster.webdav.kernel.resource.ResourceRepository;
import lombok.extern.slf4j.Slf4j;
import org.smartboot.http.common.enums.HttpStatus;

import java.io.InputStream;

/**
 * @author hongda.li
 */
@Slf4j
public class MethodDispatcherPut implements MethodDispatcher {
    @Override
    public MethodEnum supported() {
        return MethodEnum.PUT;
    }

    @Override
    public void dispatch(HttpExchange accessor) {
        Resource resource = accessor.getResource();
        ResourceRepository repository = accessor.getRepository();

        if (resource.isDirectory()) {
            log.warn("仅支持上传文件 : {}", resource.getName());
            accessor.setHttpStatus(HttpStatus.FORBIDDEN);
            return;
        }

        try {
            InputStream stream = accessor.getInputStream();
            repository.upload(resource, stream);
            log.info("上传文件成功");
            accessor.setHttpStatus(HttpStatus.CREATED);
        } catch (Exception e) {
            accessor.setHttpStatus(HttpStatus.CONFLICT);
            log.error("上传文件失败");
            repository.delete(resource);
        }
    }
}
